% This function generates one line of the simulation table on clustering.
% The setting enters the function through the variable "settings".
function [output] = output_clustering_line(setting,n_sim)

cd ../result
p_null_vec = zeros(n_sim,1); % p-value for selected G
p_adj_vec = zeros(n_sim,1); % p-value threholds for selected G
l_alt = 4; % alternatives of interest in results table
p_alt_vec = zeros(n_sim,l_alt); % p-value under alternatives
G_star_vec = zeros(n_sim,1); % selected G
estimated_size_vec = zeros(n_sim,1); 
estimated_power_vec = zeros(n_sim,1);

% p-value and thresholds for a vector of fixed G's
load('../result/results7.mat')
l_g = length(output_CCE.p_fixed_G);
p_fixed_G_mat = zeros(n_sim,l_g);
p_threshold_fixed_G_mat = zeros(n_sim,l_g);

% p-value for tradeoff alternatives
l_tradeoff = length(alt_vec_tradeoff);
p_tradeoff_mat = zeros(n_sim,l_tradeoff);


%% DATA CLEANING
i_real = 0;
for i_sim = 1 : n_sim
    s = ['results',num2str(i_sim),'.mat'];
    if exist(s, 'file') == 2
        i_real = i_real+1;
        load(s)
        eval(['output = output_',setting,';']);
        p_null_vec(i_real) = output.p_null;
        p_alt_vec(i_real,:) = output.p_alt;
        p_adj_vec(i_real,:) = output.p_adj;
        G_star_vec(i_real,:) = output.G_star;
        p_fixed_G_mat(i_real,:) = output.p_fixed_G;
        p_threshold_fixed_G_mat(i_real,:) = output.p_threshold_fixed_G;
        estimated_size_vec(i_real,:) = output.estimated_size;
        estimated_power_vec(i_real,:) = output.ave_power;
        p_tradeoff_mat(i_real,:) = output.p_tradeoff;
    end
end
p_null_vec(i_real+1:end) = [];
p_alt_vec(i_real+1:end,:) = [];
p_adj_vec(i_real+1:end,:) = [];
G_star_vec(i_real+1:end,:) = [];
p_fixed_G_mat(i_real+1:end,:) = [];
p_threshold_fixed_G_mat(i_real+1:end,:) = [];
estimated_size_vec(i_real+1:end,:) = [];
estimated_power_vec(i_real+1:end,:) = [];
p_tradeoff_mat(i_real+1:end,:) = [];
cd ../output

rej_rate_null = mean(p_null_vec<p_adj_vec); % size

rej_rate_alt = mean(p_tradeoff_mat<repmat(p_adj_vec,1,l_tradeoff)); % power

% quantiles of selected G
G_star_quantile = [quantile(G_star_vec,.25), quantile(G_star_vec,.5),...
    quantile(G_star_vec,.75)];

% vector of sizes for fixed G's
rej_rate_fixed_G = mean(p_fixed_G_mat<p_threshold_fixed_G_mat);
if l_g>8
    rej_rate_fixed_G_table = [rej_rate_fixed_G(1),rej_rate_fixed_G(5),...
        rej_rate_fixed_G(9)];
else
    rej_rate_fixed_G_table = [rej_rate_fixed_G(1),rej_rate_fixed_G(5),0];
end

estimated_size_quantile = [quantile(estimated_size_vec,.25), ...
    quantile(estimated_size_vec,.5),...
    quantile(estimated_size_vec,.75)];

estimated_power_quantile = [quantile(estimated_power_vec,.25), ...
    quantile(estimated_power_vec,.5),...
    quantile(estimated_power_vec,.75)];

output = [rej_rate_null,mean(rej_rate_alt),G_star_quantile,...
    rej_rate_fixed_G_table,estimated_size_quantile,...
    estimated_power_quantile];




